package com.atzly.community.datasource.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 获取tenantId与dbId的映射关系
 */
//@Slf4j
//@Service
public class EnterpriseDbMapService {

//    @Autowired
//    private MyConfig hjyConfig;
//
//    @Autowired
//    private EnterpriseDbMapper enterpriseDbMapper;
//
//    public BaseResponse<String> queryDbId(Long appId, Long orgId) {
//        String dbId = enterpriseDbMapper.queryDbId(appId, orgId);
//        return BaseResponse.ok(dbId);
//    }
//
//    public BaseResponse<Void> setDbId(Long appId, Long orgId, String dbId) {
//        enterpriseDbMapper.insert(appId,orgId,dbId);
//        return BaseResponse.ok();
//    }
//
//    public BaseResponse<String> queryAndAddIfEmpty(Long appId, Long orgId, String expectDbId) {
//        log.info("enterpriseDbMapper:" + enterpriseDbMapper + " " + appId + " " + orgId + " " + expectDbId);
//        String dbId = enterpriseDbMapper.queryDbId(appId, orgId);
//        log.info("queryAndAddIfEmpty： " + dbId);
//        if (StringUtil.isEmpty(dbId)) {
//            if (StringUtil.isNotEmpty(expectDbId)) {
//                dbId = expectDbId;
//                enterpriseDbMapper.insert(appId,orgId,dbId);
//            }
//        }
//        return BaseResponse.ok(dbId);
//    }
//
//    public DataSourceConfig getDataSourceConfigByTenantId(Long tenantId) {
//        ArrayDataSourceConfig dataSourceConfig = null;
//        String lockKey = "get_datasource_id:" + tenantId;
//        try {
//            Boolean acquired = DistributedLocks.tryLock(3L, 10L, TimeUnit.SECONDS, lockKey);
//
//            if(!acquired) {
//                throw new ServiceException("acquire_redis_lock_err");
//            }
//
//            Long appId = hjyConfig.getAppId();
//            Long currentTenantId = AuthContext.getTenantId();
//            TenantUtil.initContext(0L);
//            String dbId = enterpriseDbMapper.queryDbId(appId, tenantId);
//            if (StringUtil.isEmpty(dbId)) {
//                dbId = DataSourceConfigManager.getCurrentDbId(appId);
//                enterpriseDbMapper.insert(appId,tenantId,dbId);
//            }
//            dataSourceConfig = DataSourceConfigManager.getArrayDataSourceConfigByDbId(null, dbId);
//            TenantUtil.initContext(currentTenantId);
//        }catch (Exception e) {
//          log.error("获取dbid失败：",e);
//        } finally {
//            if (DistributedLocks.isLocked(lockKey)) {
//                DistributedLocks.unlock(lockKey);
//            }
//        }
//        return dataSourceConfig.getDataSourceConfigs().get(0);
//    }
//
//    public String insert(DataSourceConfig dataSourceConfig) {
//
//        String dbId = dataSourceConfig.getDbId();
//        String identification = enterpriseDbMapper.getDataSourceConfigByDbId(dbId);
//        if (StringUtil.isNotEmpty(identification)) {
//            return identification;
//        }
//        try {
//            String reg = "\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}";
//            String url = dataSourceConfig.getUrl();
//            Pattern pattern = Pattern.compile(reg, Pattern.DOTALL);
//            Matcher matcher = pattern.matcher(url);
//            if (!matcher.find()) {
//                return null;
//            }
//            String ip = matcher.group();
//            String password = dataSourceConfig.getPassword();
//            String username = dataSourceConfig.getUsername();
//            identification = dbId;
//            Long versionNo = 1L;
//            Long updaterId = 0L;
//            Long creatorId = 0L;
//            String dbPort = "3306";
//            String splitStr = "jdbc:mysql://" + ip + ":" + dbPort + "/";
//            String[] split = url.split(splitStr);
//            String[] split1 = split[1].split("\\?");
//            String dbName = split1[0];
//
//            Map<Object, Object> params = new HashMap<>();
//            params.put("versionNo",versionNo);
//            params.put("updaterId",updaterId);
//            params.put("creatorId",creatorId);
//            params.put("ip",ip);
//            params.put("id",System.currentTimeMillis());
//            params.put("dbName",dbName);
//            params.put("port",dbPort);
//            params.put("password",password);
//            params.put("username",username);
//            params.put("url",url);
//            params.put("identification",identification);
//            params.put("remarks","初始化调用接口生成");
//            enterpriseDbMapper.insertDataSourceConfig(params);
//        } catch (Exception e) {
//            log.error("数据源创建失败：{}",e.getMessage());
//            return null;
//        }
//        return identification;
//    }
//
//    public static void main(String[] args) throws InterruptedException {
////        String reg = "\\d{1,3}.\\d{1,3}.\\d{1,3}.\\d{1,3}";
////        String url = "jdbc:mysql://59.110.235.142:3306/hjy?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8&rewriteBatchedStatements=true";
////        Pattern pattern = Pattern.compile(reg, Pattern.DOTALL);
////        Matcher matcher = pattern.matcher(url);
////        matcher.find();
////        String ip = matcher.group();
////        String dbPort = "3306";
////        String splitStr = "jdbc:mysql://" + ip + ":" + dbPort + "/";
////        System.out.println(splitStr);
////        String[] split = url.split(splitStr);
////        String[] split1 = split[1].split("\\?");
////        String dbName = split1[0];
////        System.out.println(dbName);
//        final String lockKey = "get_datasource_id:1" ;
//        new Thread(new Runnable() {
//            @SneakyThrows
//            @Override
//            public void run() {
//                Boolean acquired = DistributedLocks.tryLock(3L, 10L, TimeUnit.SECONDS, lockKey);
//                System.out.println(acquired);
//                Thread.sleep(4000);
//                DistributedLocks.unlock(lockKey);
//            }
//        }).start();
//        Thread.sleep(2000);
//        new Thread(new Runnable() {
//            @SneakyThrows
//            @Override
//            public void run() {
//                Boolean acquired = DistributedLocks.tryLock(10L, 10L, TimeUnit.SECONDS, lockKey);
//                System.out.println(acquired);
//            }
//        }).start();
//
//
//    }

}
